﻿using CoreLib;
using Domain.Repository;
using Domain.Repository.RequestModels;
using Domain.Repository.ResponseModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UI.Extensions;
using UI.Models;
using UI.Models.LayuiResponse;

namespace UI.Api
{
    /// <summary>
    /// route begins with mobile
    /// </summary>
    [Route("api/[controller]")]
    [ApiController, Authorize]
    public class ApproveController : ControllerBase
    {
        private readonly ITaskNodeRepository _taskNodeRepository;
        private readonly ITaskRepository _taskRepository;
        private readonly ISystemClock _systemClock;
        private readonly string _currentUser;

        public ApproveController(
            IHttpContextAccessor httpContextAccessor,
            ITaskNodeRepository taskNodeRepository,
            ITaskRepository taskRepository,
            ISystemClock systemClock)
        {
            _currentUser = httpContextAccessor.HttpContext.User.Identity.Name;
            _taskNodeRepository = taskNodeRepository ?? throw new ArgumentNullException(nameof(taskNodeRepository));
            _taskRepository = taskRepository ?? throw new ArgumentNullException(nameof(taskRepository));
            _systemClock = systemClock ?? throw new ArgumentNullException(nameof(systemClock));
        }

        [HttpGet("GetTaskNodeLstByPage")]
        public async Task<TableResponse<TaskNodeModel>> GetTaskNodeLstByPage(int page = 1, int limit = 10)
        {
            var aTargetType = Request.Query["aTargetType"].FirstOrDefault() ?? "OTCTRADE";
            var time = Request.Query["time"].FirstOrDefault();
            var groupCode = Request.Query["aGroupCode"].FirstOrDefault() ?? "0";

            var dataType = "0";
            string begin, end;
            if (string.IsNullOrWhiteSpace(time))
            {
                begin = _systemClock.Now.AddDays(-14).ToString("yyyy-MM-dd");
                end = _systemClock.Now.AddDays(1).ToString("yyyy-MM-dd");
            }
            else
            {
                var range = time.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);

                begin = range[0];
                end = range[1];
            }

            var response = await _taskNodeRepository.MobileGetTaskNodeLstByPage(new MobileGetTaskNodeLstByPageRequestModel
            {
                aPage = 0,  //  没有页面请求数量，因此获取所有
                aBegdate = begin,
                aEnddate = end,
                aTargetType = aTargetType,
                aUserCode = _currentUser,
                aDataType = dataType,
                aGroupCode = groupCode
            });

            return new TableResponse<TaskNodeModel>
            {
                code = 0,
                count = response.rt.TLlist.Count(),    //  组合里面的数量与实际的数量不一致
                data = response.rt.TLlist.Select(r => new TaskNodeModel
                {
                    CASHDIRECTION = r.CASHDIRECTION,
                    GR = r.GR,
                    ID = r.ID,
                    ISCCROLE = bool.Parse(r.ISCCROLE),
                    NID = r.NID,
                    OR = r.OR,
                    TID = r.TID,
                    TY = r.TY,
                    R = r.R.Select(t => new Models.NameTextModel
                    {
                        NAME = t.NAME,
                        text = t.txt,
                    })
                }).Skip(limit * (Math.Max(0, page - 1))).Take(limit)
            };
        }

        [HttpGet("MobileGetTaskNodeGroup")]
        public async Task<TableResponse<GroupG>> MobileGetTaskNodeGroup()
        {
            var aTargetType = Request.Query["aTargetType"].FirstOrDefault() ?? "OTCTRADE";
            var time = Request.Query["time"].FirstOrDefault();

            var dataType = "0";
            string begin, end;
            if (string.IsNullOrWhiteSpace(time))
            {
                begin = _systemClock.Now.AddDays(-14).ToString("yyyy-MM-dd");
                end = _systemClock.Now.AddDays(1).ToString("yyyy-MM-dd");
            }
            else
            {
                var range = time.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);

                begin = range[0];
                end = range[1];
            }

            var response = await _taskNodeRepository.MobileGetTaskNodeGroup(new MobileGetTaskNodeGroupRequestModel
            {
                aBeg_date = begin,
                aEnd_date = end,
                aTargetType = aTargetType,
                aUserCode = _currentUser,
                aDataType = dataType,
            });

            return await Task.FromResult(new TableResponse<GroupG>
            {
                code = 0,
                data = response.rt.G
            });
        }

        [HttpGet("SingleTaskNodeTree")]
        public async Task<TableResponse<TreeTableModelResponse>> GetSingleTaskNodeTree(string taskId)
        {
            var response = await _taskRepository.MobileSingleTaskNodeTree(new BaseRequestModel
            {
                aTaskId = taskId,
                aUserCode = _currentUser
            });

            return new TableResponse<TreeTableModelResponse>
            {
                code = 0,
                data = response.rt.T.ToTree<TreeTableModelResponse>()
            };
        }


        [HttpGet("traceLog")]
        public async Task<TableResponse<TraceLogTL>> GetSingleTraceLog(string taskId)
        {
            var response = await _taskRepository.MobileSingleTraceLog(new BaseRequestModel
            {
                aTaskId = taskId,
                aUserCode = _currentUser
            });

            return new TableResponse<TraceLogTL>
            {
                code = 0,
                data = response.rt.TLlist
            };
        }

        [HttpGet("limit")]
        public async Task<TableResponse<SinglelimitTL>> MobileSingleLimitresult(string taskId)
        {
            var response = await _taskRepository.MobileSingleLimitresult(new MobileSingleLimitRequestModel
            {
                aTaskId = taskId,
                aUserCode = _currentUser
            });

            return new TableResponse<SinglelimitTL>
            {
                code = 0,
                data = response.rt.TLlist
            };
        }

        [HttpPost("MobileCheckBeforeActionByNodeId_Batch")]
        public async Task<CheckBatchResponseModel> MobileCheckBeforeActionByNodeId_Batch(PreBatchCheckModel model)
        {
            var response = await _taskRepository.MobileCheckBeforeActionByNodeId_Batch(new MobileCheckBeforeActionByNodeIdBatchRequestModel
            {
                aNodeIds = string.Join(',', model.nids),
                targetType = model.targetType,
                aDataTypeCurrent = model.aDataTypeCurrent,
                aUserCode = _currentUser
            });

            return response;
        }
        public class GenRtl
        {
            public bool success { get; set; }

            public string message { get; set; }
        }
        [HttpPost("MobileApproveTaskByNodeId_Batch")]
        public async Task<GenRtl> MobileApproveTaskByNodeId_Batch(BatchApproveModel model)
        {
            await _taskRepository.MobileApproveTaskByNodeId_Batch(new MobileApproveTaskByNodeId_BatchRequestModel
            {
                aNodeIds = string.Join(',', model.nids),
                targetType = model.targetType,
                aDataTypeCurrent = model.aDataTypeCurrent,
                aUserCode = _currentUser,
                actionNote = model.actionNote,
                aAction = model.aAction,
                aCCRoles = null
            });

            return new GenRtl { success = true, message = "操作成功" };
        }
    }
}
